import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';

// 默认分页size
const DEFAULT_LIMIT = 50; // 增加默认加载数量

export async function GET(req: NextRequest) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { searchParams } = new URL(req.url);
    const conversationId = searchParams.get('conversationId');
    const cursor = searchParams.get('cursor');
    const limit = parseInt(searchParams.get('limit') || `${DEFAULT_LIMIT}`, 10);

    if (!conversationId) {
      return NextResponse.json({ error: '必须提供 conversationId' }, { status: 400 });
    }

    // 验证用户是否是会话的参与者
    const participation = await prisma.conversationParticipant.findFirst({
      where: {
        conversationId: conversationId,
        userId: userId,
      },
    });

    if (!participation) {
      return NextResponse.json({ error: '你无权访问此会话' }, { status: 403 });
    }

    const messages = await prisma.message.findMany({
      take: limit,
      ...(cursor && {
        skip: 1,
        cursor: { id: cursor },
      }),
      where: {
        conversationId: conversationId,
      },
      orderBy: {
        createdAt: 'desc',
      },
      include: {
        sender: {
          select: {
            id: true,
            username: true,
            avatar: true,
          },
        },
      },
    });

    let nextCursor = null;
    if (messages.length === limit) {
      nextCursor = messages[messages.length - 1].id;
    }

    // 返回的消息应该是正序的，方便前端展示
    return NextResponse.json({
      messages: messages.reverse(),
      nextCursor,
    });

  } catch (error) {
    console.error('获取历史消息失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 